import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from './utils/get-page-title'

const whiteList = ['/login', '/404']

router.beforeEach(async(to, from, next) => {
  // 开启进度条
  NProgress.start()
  if (store.getters.token) {
    // 有token
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const { roles: { menus }} = await store.dispatch('user/getUserInfo')

        // console.log(await store.dispatch('user/getUserInfo'))

        const otherRoutes = await store.dispatch('permissions/filterRoutes', menus)

        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        // addRoutes 是异步的需要重新走一遍beforeEach
        // replace: true 不会生成新的历史记录
        return next({
          ...to,
          replace: true
        })
      }
      next()
    }
  } else {
    // 无token
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  // 注意：如果在路由全局前置导航守卫中，通过 next 拦截到了其他页面，后置守卫不会被触发
  NProgress.done()
})

// 后置守卫
router.afterEach((to) => {
  document.title = getPageTitle(to.meta.title)
  // 关闭进度条
  NProgress.done()
})
